package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.Role;
import com.example.demo.entity.UserRole;
import com.example.demo.mapper.RoleMapper;
import com.example.demo.mapper.UserRoleMapper;
import com.example.demo.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author moguai
 * @version 1.0
 * @date 2022/3/18 19:58
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {
    @Autowired(required = false)
    UserRoleMapper userRoleMapper;
    @Autowired(required = false)
    RoleMapper roleMapper;


    @Override
    public void insertUserRole(Integer user_id, Integer roleId) {
        UserRole user_role = new UserRole(user_id, roleId);
        this.save(user_role);
    }

    @Override
    public void deleteUserRole(Integer user_id, Integer roleId) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("role_id", roleId);
        userRoleMapper.deleteByMap(map);
    }

    @Override
    public void deleteByIds(String name, List<Integer> ids) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(name, ids);
        userRoleMapper.delete(queryWrapper);
    }

    @Override
    public List<Integer> selectRoleIdByUser(Integer userId) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userId);
        List<UserRole> userRoles = userRoleMapper.selectList(queryWrapper);
        List<Integer> roleId = userRoles.stream().map(UserRole::getRole_id).collect(Collectors.toList());
        return roleId;
    }

    @Override
    public List<UserRole> selectUserRoleByRole(Integer roleId) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("role_id", roleId);
        List<UserRole> user_Roles = userRoleMapper.selectList(queryWrapper);
        return user_Roles;
    }

    @Override
    public List<Role> selectRoleByUser(Integer userId) {
        List<Integer> roleId = this.selectRoleIdByUser(userId);
        if (null == roleId || roleId.size() == 0) {
            return null;
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.in("role_id", roleId);
        List<Role> list = roleMapper.selectList(wrapper);
        return list;
    }
}
